home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / pluginy Firefox / 8206 / 8206.xpi / content / options.js < prev    next >
Text File  |  2010-02-02  |  47KB  |  1,488 lines

  1. var WiseStampOptions = function ()
  2. {
  3.     var pub = {};
  4.  
  5.     // public consts
  6.     pub.PREFS = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.wisestamp.");
  7.     pub.BUNDLE = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService).createBundle("chrome://wisestamp/locale/wisestamp.properties");
  8.  
  9.     // public vars
  10.     pub.type = null;
  11.     pub.data =
  12.     {
  13.         _startType: null,
  14.         type: null,
  15.         sigs:
  16.         {}
  17.     };
  18.  
  19.     // private vars
  20.     var DEFAULT_TYPE = "special-default";
  21.     var settings =
  22.     {
  23.         signatures: [],
  24.         autoinsert_compose: true,
  25.         autoinsert_thread: true,
  26.         hidebuttons: false,
  27.         hidestatusbar: false,
  28.         promote: true
  29.     }
  30.     
  31.     var config_sig = [
  32.         {
  33.             id: "signature_types_popup",
  34.             prefix: "type_",
  35.             stopEle: "signature_types_separater"
  36.         },
  37.         {
  38.             id: "manage_sig_box",
  39.             prefix: "type_box_",
  40.             stopEle: "manage_new_container"
  41.     }]
  42.  
  43.     var userLoggedIn = false;
  44.     var userEmail = null;
  45.     var userPassword = null;
  46.  
  47.     var userEmail = null;
  48.     var userPassword = null;
  49.     
  50.     var SUPPORT_MULTI_SIG = false;
  51.     var SUPPORT_PREMIUM = WiseStampPrefs.getBoolPref("premium",false);
  52.  
  53.     var editorMode = "wysiwyg";
  54.     
  55.     // public functions
  56.     pub.getTypeShortName = function (aType)
  57.     {
  58.         return encodeURIComponent(aType.replace(/^\s+|\s+$/, "").toLowerCase());
  59.     };
  60.  
  61.     function updatePremiumSupport()
  62.     {
  63.         WiseStampUtils.log("options.js :: updatePremiumSupport :: supported = " + SUPPORT_PREMIUM);
  64.         
  65.         document.getElementById("signature_types_separater").hidden = !SUPPORT_PREMIUM;
  66.         document.getElementById("signature_types_premium").hidden = !SUPPORT_PREMIUM;
  67.         document.getElementById("signature_types_create").hidden = !SUPPORT_PREMIUM;
  68.  
  69.         document.getElementById("createSignaturePremium").hidden = !SUPPORT_PREMIUM;
  70.         
  71.         if (!SUPPORT_PREMIUM)
  72.         {
  73.             var prefwin = document.getElementById("BrowserPreferences");
  74.             prefwin.removeChild(document.getElementById("paneSecurity"));
  75.             prefwin.removeChild(document.getElementById("paneApplications"));
  76.             prefwin.removeChild(document.getElementById("paneContent"));
  77.         }
  78.     }
  79.     
  80.     function updateMultipleSignaturesSupport(supported)
  81.     {
  82.         WiseStampUtils.log("[options.js :: updateMultipleSignaturesSupport] supported = " + supported);
  83.             
  84.         document.getElementById("createSignatureFromDlg").hidden = !supported;
  85.         document.getElementById("createSignaturePremium").hidden = !SUPPORT_PREMIUM || supported;
  86.         
  87.         var deleteLabels = document.getElementById(config_sig[1].id).getElementsByTagName("label");
  88.         WiseStampUtils.log("[options.js :: updateMultipleSignaturesSupport] deleteLabels.length = " + deleteLabels.length);
  89.         for (var i = 0; i < deleteLabels.length; i++)
  90.             deleteLabels[i].hidden = !supported;
  91.  
  92.         document.getElementById("manage_sig_scroll").setAttribute("style","overflow-y: "+(supported ? "scroll" : "auto") + "; overflow-x: hidden;");
  93.         document.getElementById("signature_types_create").hidden = !supported;
  94.         document.getElementById("signature_types_premium").hidden = !SUPPORT_PREMIUM || supported;
  95.         
  96.         WiseStampUtils.log("[options.js :: updateMultipleSignaturesSupport] <<<<<");
  97.     }
  98.     
  99.     pub.onLoad = function (event)
  100.     {
  101.         WiseStampUtils.log("[options.js :: onLoad] >>>>> ");
  102.         WisestampGetAppObject().updateUI();
  103.         
  104.         loadData();
  105.         var editor = document.getElementById("signature-wysiwyg");
  106.         loadSignaturesList(0);
  107.         if (pub.data.type == "none") 
  108.             pub.setCurrentSignature("personal", true);
  109.         else 
  110.             pub.setCurrentSignature(pub.data.type, true);
  111.         
  112.         pub.loginInBackground();
  113.         
  114.         WiseStampComm.writeLog(WiseStampComm.LOG_EVENT_SETTINGS);
  115.  
  116.         updatePremiumSupport();
  117.                 
  118.         if (WiseStampUtils.getDebugMode() == false)
  119.         {
  120.             document.getElementById("BrowserPreferences").removeChild(document.getElementById("panePrivacy"));
  121.             document.getElementById("BrowserPreferences").removeChild(document.getElementById("paneSubmitBug"));
  122.         }
  123.             
  124.         WiseStampUtils.log("[options.js :: onLoad] <<<<<");
  125.     }
  126.  
  127.     pub.createNewSigFromMenu = function (event)
  128.     {
  129.         WiseStampUtils.log("options.js :: createNewSigFromMenu :: >>>>>");
  130.         
  131.         var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  132.         var check = { value: null };
  133.         var input = { value: "" }; // default the edit field to Bob      
  134.         var result = prompts.prompt(window, pub.BUNDLE.GetStringFromName("newsigTitle"), pub.BUNDLE.GetStringFromName("newsig"), input, null, check);
  135.         var success = false;
  136.         if (result && input.value != "") 
  137.             success = addNewSignatureFromMenu(input.value, event);
  138.             
  139.         event.preventDefault();
  140.         event.stopPropagation();
  141.         /* select last signature */
  142.         var container = document.getElementById("signature_types_popup");
  143.         var toSelect = container.childNodes.length - 3;
  144.         if (toSelect >= 0) 
  145.             container.parentNode.selectedIndex = toSelect;
  146.             
  147.         if (success) 
  148.             pub.setCurrentSignature(getTypeShortName(input.value), true);
  149.     }
  150.  
  151.     pub.loadSettings = function ()
  152.     {
  153.         document.getElementById("autoinsert_compose").checked = WiseStampPrefs.getBoolPref("autoinsert_compose", true, "autoinsert");
  154.         document.getElementById("autoinsert_thread").checked = WiseStampPrefs.getBoolPref("autoinsert_thread", true, "autoinsert");
  155.         document.getElementById("hidebuttons").checked = pub.PREFS.getBoolPref("hidebuttons");
  156.         document.getElementById("hidestatusbar").checked = pub.PREFS.getBoolPref("hidestatusbar");
  157.  
  158.         document.getElementById("promoteChk").checked = pub.PREFS.getBoolPref("promote");
  159.  
  160.         settings.signatures = WiseStampUtils.getSignaturesFromPref();
  161.         pub.showHideHelpus();
  162.         
  163.         setTimeout(function () { loadSignaturesList(1); }, 0);
  164.     }
  165.  
  166.     pub.validateRss = function (status) 
  167.     {
  168.         if (status != "refreshed") 
  169.         {
  170.             document.getElementById("rss-valid").value = "Validating...";
  171.             document.getElementById("rss-valid").setAttribute("status", "");
  172.             var url = document.getElementById("rss-url").value;
  173.             feedBlog = new WiseStampFeedWrapper(new WiseStampRSSFeed(url), new WiseStampPostFormatter());
  174.             //valid_timer = window.setTimeout(function () { WiseStampOptions.validateRss("refreshed"); }, 5000);
  175.             feedBlog.refreshCache(function () {
  176.                 setTimeout(function () { WiseStampOptions.validateRss("refreshed"); }, 0);
  177.             });
  178.             
  179.             //window.setTimeout(function () { throw new Error("[debug] " + "1 - " + feedBlog._feed.url); }, 0);
  180.         
  181.         } else 
  182.         {
  183.             //window.setTimeout(function () { throw new Error("[debug] " + "3 - " + feedBlog); }, 0);
  184.             //window.setTimeout(function () { throw new Error("[debug] " + "4 - " + feedBlog.format()); }, 0);
  185.             
  186.             if (feedBlog.format()) {
  187.                 document.getElementById("rss-valid").value = "OK";
  188.                 document.getElementById("rss-valid").setAttribute("status", "ok");
  189.             } else {
  190.                 document.getElementById("rss-valid").value = "Couldn't validate the feed. Please check the link.";
  191.                 document.getElementById("rss-valid").setAttribute("status", "error");
  192.             }
  193.         }
  194.     }
  195.  
  196.     pub.setCurrentAsDefault = function ()
  197.     {
  198.         pub.data.type = pub.type;
  199.         pub.PREFS.setCharPref("type", pub.data.type);
  200.         var setdefault = document.getElementById("setasdefault");
  201.         var isdefault = document.getElementById("isdefault");
  202.         setdefault.hidden = true;
  203.         isdefault.hidden = false;
  204.     }
  205.  
  206.     pub.setCurrentSignature = function (aType, uninit)
  207.     {
  208.         WiseStampUtils.log("[options.js :: setCurrentSignature] aType = " + aType);
  209.         
  210.         if (aType == "")
  211.             return;
  212.             
  213.         if (pub.type && uninit)
  214.             storeData(pub.type);
  215.         
  216.         pub.type = aType;
  217.         
  218.         initGeneral();
  219.         initEditor();
  220.         initIM();
  221.         initServices();
  222.         
  223.         WiseStampUtils.log("[options.js :: setCurrentSignature] <<<<<");
  224.     }
  225.  
  226.     pub.toggleAdvanced = function (mode)
  227.     {
  228.         var show = document.getElementById("advanced-show");
  229.         var hide = document.getElementById("advanced-hide");
  230.         if (mode == "html")
  231.         {
  232.             show.hidden = false;
  233.             hide.hidden = true;
  234.             document.getElementById("signature-html-deck").selectedIndex = 0;
  235.             
  236.         } else if (mode == "advanced")
  237.         {
  238.             show.hidden = true;
  239.             hide.hidden = false;
  240.             document.getElementById("signature-html-deck").selectedIndex = 1;
  241.         }
  242.     }
  243.  
  244.     pub.toggleEditor = function (event)
  245.     {
  246.         var container = document.getElementById("editor-container");
  247.         var mode = container.getAttribute("mode");
  248.         if (mode == "wysiwyg")
  249.         { //show plain html
  250.             editorMode = "html";
  251.             container.setAttribute("mode", editorMode);
  252.             //event.target.setAttribute("label","&showwysiwyg;");
  253.             //event.target.label = "&showwysiwyg;";
  254.             document.getElementById("editor-toggle-wysiwyg").hidden = false;
  255.             document.getElementById("editor-toggle-html").hidden = true;
  256.  
  257.             var wysiwyg = document.getElementById("signature-wysiwyg");
  258.             var text = wysiwyg.contentDocument.body.innerHTML.replace(/<br\/?>+$/, "");
  259.             var editor = document.getElementById("signature-html");
  260.             //setSourceEditorValue(text,editor);
  261.             editor.value = text;
  262.             pub.toggleAdvanced("html");
  263.             document.getElementById("editor-deck").selectedIndex = 1; //Panel = editor;
  264.             document.getElementById("editor-toolbar-deck").selectedPanel = document.getElementById("editor-toolbar-replacement");
  265.         } else if (mode == "html") //show what you see is what you get editor
  266.         {
  267.             editorMode = "wysiwyg";
  268.             container.setAttribute("mode", editorMode);
  269.             //event.target.setAttribute("label","&showhtml;");
  270.             //event.target.label = "showhtml";
  271.             document.getElementById("editor-toggle-wysiwyg").hidden = true;
  272.             document.getElementById("editor-toggle-html").hidden = false;
  273.  
  274.             var html = document.getElementById("signature-html");
  275.             var text = html.value.replace(/(\n|\s)+$/gm, "");
  276.             //var text  = getSourceEditorValue();
  277.             var editor = document.getElementById("signature-wysiwyg");
  278.             editor.contentDocument.body.innerHTML = text;
  279.             document.getElementById("editor-deck").selectedIndex = 0; //Panel = editor;
  280.             document.getElementById("editor-toolbar-deck").selectedPanel = document.getElementById("editor-toolbar-container");
  281.         }
  282.     }
  283.  
  284.     pub.addNewService = function ()
  285.     {
  286.         var container = document.getElementById("social-services");
  287.         var services = pub.PREFS.getCharPref("services").split(",");
  288.         var loaded = container.getAttribute("value").split(",");
  289.         for (var i = 0; i < services.length; i++)
  290.         {
  291.             var sid = services[i];
  292.             if (loaded.indexOf(sid) == -1 || i == services.length - 1)
  293.             {
  294.                 var menuitem = document.createElement("wisestamp-service");
  295.                 menuitem.setAttribute("service", sid);
  296.                 if (!pub.data.sigs[pub.type].services[sid]) 
  297.                     pub.data.sigs[pub.type].services[sid] = [];
  298.                     
  299.                 var val = pub.data.sigs[pub.type].services[sid][pub.data.sigs[pub.type].services[sid].length];
  300.                 if (val) 
  301.                     menuitem.setAttribute("value", val);
  302.                     
  303.                 /* the last child is the add more label */
  304.                 container.appendChild(menuitem);
  305.                 container.setAttribute("value", container.getAttribute("value") + "," + sid);
  306.                 var scroll = document.getElementById("socialservices-scroll");
  307.                 scroll.boxObject.QueryInterface(Components.interfaces.nsIScrollBoxObject).ensureElementIsVisible(menuitem);
  308.                 return;
  309.             }
  310.         }
  311.     }
  312.  
  313.     pub.addNewIM = function ()
  314.     {
  315.         var container = document.getElementById("im-box");
  316.         var services = pub.PREFS.getCharPref("im").split(",");
  317.         var loaded = container.getAttribute("value").split(",");
  318.         for (var i = 0; i < services.length; i++)
  319.         {
  320.             var sid = services[i];
  321.             if (loaded.indexOf(sid) == -1 || i == services.length - 1)
  322.             {
  323.                 var menuitem = document.createElement("wisestamp-im");
  324.                 menuitem.setAttribute("service", sid);
  325.  
  326.                 var val = pub.data.sigs[pub.type].im[sid][pub.data.sigs[pub.type].im[sid].length];
  327.                 if (val) 
  328.                     menuitem.setAttribute("value", val);
  329.                     
  330.                 menuitem.setAttribute("width", "170");
  331.                 
  332.                 /* the last child is the add more label */
  333.                 container.appendChild(menuitem);
  334.                 container.setAttribute("value", container.getAttribute("value") + "," + sid);
  335.                 var scroll = document.getElementById("imservices-scroll");
  336.                 scroll.boxObject.QueryInterface(Components.interfaces.nsIScrollBoxObject).ensureElementIsVisible(menuitem);
  337.                 return;
  338.             }
  339.         }
  340.     }
  341.  
  342.     pub.previewSignature = function ()
  343.     {
  344.         storeData(pub.type);
  345.         storeSettings();
  346.         
  347.         openDialog("chrome://wisestamp/content/preview.xul","wisestamp:preview","chrome,centerscreen,resizable,width=550,height=250",{data: pub.data.sigs[pub.type], settings: settings});
  348.     }
  349.  
  350.     function applySettings()
  351.     {
  352.         if (updateRenamedSigs() == false) 
  353.             return false;
  354.  
  355.         storeData(pub.type);
  356.         
  357.         pub.PREFS.setCharPref("type", pub.data.type);
  358.         for (var sig in pub.data.sigs)
  359.         {
  360.             saveSignatureToConfig(sig);
  361.         }
  362.  
  363.         saveSettings();
  364.     }
  365.     
  366.  
  367.     pub.onOK = function ()
  368.     {
  369.         try
  370.         {
  371.             var focused = document.commandDispatcher.focusedElement;
  372.             var focused_id = focused.parentNode.parentNode.id;
  373.  
  374.             if (focused_id == "email_edit" || focused_id == "password_edit")
  375.             {
  376.                 this.onLogin();
  377.                 return false;
  378.             }
  379.         } catch (e) {}
  380.         
  381.         applySettings();
  382.         saveSignaturesToServer();
  383.  
  384.         WisestampGetAppObject().saveSignature(pub.data.type);
  385.         
  386.         document.getElementById("BrowserPreferences").setAttribute("lastSelected","paneMain");
  387.         
  388.         this.onClose(); 
  389.         return true;
  390.     }
  391.  
  392.     pub.onClose = function ()
  393.     {
  394.         document.getElementById("BrowserPreferences").setAttribute("lastSelected","paneMain");
  395.         return true; 
  396.     }
  397.     
  398.     pub.deleteSignature = function (aType, removeAll)
  399.     {
  400.         WiseStampUtils.log("options.js :: deleteSignature :: deleting signature '" + aType + "'");
  401.         if (!removeAll)
  402.         {
  403.             /* Don't let them remove the last signature */
  404.             if (settings.signatures.length == 1)
  405.             {
  406.                 WiseStampUtils.alert("deletesignatureerr", "deletesignaturetitle");
  407.                 return;
  408.             } 
  409.             
  410.             var confirmed = WiseStampUtils.confirm("deletesignaturetitle", "deletesignatureconfirm");
  411.             if (confirmed == 1) 
  412.                 return;
  413.         }
  414.         
  415.         var ltype = getTypeShortName(aType);
  416.  
  417.         /* remove signature from menulist dropdown popup */
  418.         var container = document.getElementById("signature_types_popup");
  419.         var nodes = container.childNodes;
  420.  
  421.         var len = nodes.length;
  422.         for (var i = 0; i < len; i++)
  423.         {
  424.             if (nodes[i].getAttribute("value") == ltype)
  425.             {
  426.                 /* remove node */
  427.                 container.removeChild(nodes[i]);
  428.                 break;
  429.             }
  430.         }
  431.         
  432.         /* remove signature from groupbox in settings pane */
  433.         container = document.getElementById("manage_sig_box");
  434.         nodes = container.childNodes;
  435.         len = nodes.length;
  436.         for (var i = 0; i < len; i++)
  437.         {
  438.             try
  439.             {
  440.                 var nval = getTypeShortName(nodes[i].getAttribute("value"));
  441.                 if (nval == ltype)
  442.                 {
  443.                     /* remove node */
  444.                     container.removeChild(nodes[i]);
  445.                     break;
  446.                 }
  447.             } catch(e) {}
  448.             /*a text element... If we used a box this wouldn't happen, but we need the div to wrap the elements like we want */
  449.         }
  450.         
  451.         /* remove from sig list */
  452.         for (var i = 0; i < settings.signatures.length; i++)
  453.         {
  454.             if (getTypeShortName(settings.signatures[i]) == ltype)
  455.                 break;
  456.         }
  457.  
  458.         settings.signatures.splice(i, 1);
  459.  
  460.  
  461.         if (removeAll == false) // if some left
  462.         {
  463.             if (pub.type == ltype)
  464.             {
  465.                 /* We are removing the current signature, reload the next sig */
  466.                 var newtype = getTypeShortName(settings.signatures[settings.signatures.length - 1]);
  467.                 pub.data.sigs[newtype];
  468.                 pub.type = null; //Prevent the current type from being saved
  469.                 
  470.                 pub.setCurrentSignature(newtype, true);
  471.             }
  472.             
  473.             if (ltype == pub.data.type)
  474.             {
  475.                 /*If it is the default, set a new default sig */
  476.                 pub.type = getTypeShortName(settings.signatures[0]);
  477.                 pub.setCurrentAsDefault();
  478.             }
  479.         }
  480.         
  481.         //WiseStampUtils.setSignaturesToPref(settings.signatures);
  482.         
  483.         /* remove old signature from preferences */
  484.         WiseStampPrefs.clearBranch(ltype);
  485.         
  486.         pub.data.sigs[ltype] = null;
  487.         delete pub.data.sigs[ltype];
  488.         
  489.         WiseStampUtils.log("options.js :: deleteSignature <<<<");
  490.     }
  491.  
  492.     pub.showHideHelpus = function ()
  493.     {
  494.         var promote = document.getElementById("promoteChk").checked;
  495.         if (!promote) 
  496.             document.getElementById("helpusDeck").selectedIndex = 1;
  497.         else 
  498.             document.getElementById("helpusDeck").selectedIndex = 0;
  499.     }
  500.  
  501.     // private functions
  502.     function getTypeShortName(aType)
  503.     {
  504.         return encodeURIComponent(aType.replace(/^\s+|\s+$/, "").toLowerCase());
  505.     }
  506.  
  507.     function loadSignaturesList(aMode)
  508.     {
  509.         var container = document.getElementById(config_sig[aMode].id);
  510.         //Erase existing items
  511.         while ((container.firstChild instanceof XULElement && container.firstChild.getAttribute && container.firstChild.getAttribute("id")!=config_sig[aMode].stopEle) ||
  512.                 !(container instanceof Element))    
  513.         {
  514.             container.removeChild(container.firstChild);
  515.         }
  516.         
  517.         var signatures = WiseStampUtils.getSignaturesFromPref();
  518.         signatures.forEach(function (item) { addNewSignatureElement(aMode, item); }, this);
  519.         updateMultipleSignaturesSupport(SUPPORT_MULTI_SIG);
  520.     }
  521.  
  522.     function addNewSignatureElement(aMode, item)
  523.     {
  524.         WiseStampUtils.log("options.js :: addNewSignatureElement >>>");
  525.         if (!item && item == "") 
  526.             return;
  527.             
  528.         var ele;
  529.         container = document.getElementById(config_sig[aMode].id);
  530.         if (!container) 
  531.             container = document.getElementById(config_sig[aMode].id);
  532.             
  533.         if (aMode == 0) {
  534.             /* menulist dropdown box */
  535.             ele = document.createElement("menuitem");
  536.             ele.setAttribute("label", item);
  537.             ele.setAttribute("value", getTypeShortName(item));
  538.             ele.setAttribute("id", config_sig[aMode].prefix + getTypeShortName(item));
  539.             container.insertBefore(ele, document.getElementById("signature_types_separater"));
  540.         
  541.         } else if (aMode == 1) /* groupbox */
  542.         {
  543.             ele = document.createElement("hbox");
  544.             ele.setAttribute("value",item);
  545.             
  546.             var txt = document.createElement("textbox");
  547.             txt.setAttribute("value",item);
  548.             txt.setAttribute("width","120")
  549.             
  550.             var deleteLbl = document.createElement("label");
  551.             deleteLbl.setAttribute("value", "Delete");
  552.             deleteLbl.setAttribute("class", "text-link");
  553.             deleteLbl.setAttribute("onclick", "WiseStampOptions.deleteSignature('" + item + "',false)");
  554.             
  555.             ele.appendChild(txt);
  556.             ele.appendChild(deleteLbl);
  557.             
  558.             container.insertBefore(ele,document.getElementById("manage_new_container"));
  559.             
  560.             var scroll = document.getElementById("manage_sig_scroll");
  561.             scroll.boxObject.QueryInterface(Components.interfaces.nsIScrollBoxObject).ensureElementIsVisible(txt);
  562.             var x = {value: null}, y = {value: null};
  563.             scroll.boxObject.QueryInterface(Components.interfaces.nsIScrollBoxObject).getScrolledSize(x,y);
  564.             scroll.boxObject.QueryInterface(Components.interfaces.nsIScrollBoxObject).scrollTo(x.value,y.value);
  565.         }
  566.     }
  567.  
  568.     function addNewSignatureFromMenu(value, event)
  569.     {
  570.         WiseStampUtils.log("options.js :: addNewSignatureFromMenu :: >>>>>");
  571.         
  572.         value = value.replace(/^\s+|\s+$/, "");
  573.         var lvalue = encodeURIComponent(value.toLowerCase());
  574.         if (!lvalue || lvalue == "") 
  575.             return false;
  576.             
  577.         var exists = settings.signatures.some(function (sig) { return encodeURIComponent(sig.toLowerCase()) == lvalue; });
  578.         if (!exists)
  579.         {
  580.             addNewSignatureElement(1, value);
  581.             addNewSignatureElement(0, value);
  582.             pub.data.sigs[lvalue] = loadSignatureFromConfig(DEFAULT_TYPE);
  583.             /* load default settings */
  584.             saveSignatureToConfig(lvalue);
  585.             settings.signatures.push(value);
  586.             return true;
  587.         
  588.         } else
  589.             WiseStampUtils.alert("errorsigexists");
  590.  
  591.         return false;
  592.     }
  593.  
  594.     // Process to delete: Get small type, If no signatures left, don't delete, Remove elements from menulist and manage list, If current, 
  595.     //                             select next signature, Remove preferences for that signatures
  596.     function storeSettings()
  597.     {
  598.         settings.autoinsert_compose = document.getElementById("autoinsert_compose").checked;
  599.         settings.autoinsert_thread = document.getElementById("autoinsert_thread").checked;
  600.         settings.hidebuttons = document.getElementById("hidebuttons").checked;
  601.         settings.hidestatusbar = document.getElementById("hidestatusbar").checked;
  602.  
  603.         settings.promote = document.getElementById("promoteChk").checked;
  604.     }
  605.  
  606.     function saveSettings()
  607.     {
  608.         storeSettings();
  609.         pub.PREFS.setBoolPref("autoinsert_compose", settings.autoinsert_compose);
  610.         pub.PREFS.setBoolPref("autoinsert_thread", settings.autoinsert_thread);
  611.         pub.PREFS.setBoolPref("hidebuttons", settings.hidebuttons);
  612.         pub.PREFS.setBoolPref("hidestatusbar", settings.hidestatusbar);
  613.  
  614.         pub.PREFS.setBoolPref("promote", settings.promote);
  615.  
  616.         WiseStampUtils.setSignaturesToPref(settings.signatures);
  617.     }
  618.  
  619.     function loadData()
  620.     {
  621.         pub.data._startType = pub.data.type = pub.PREFS.getCharPref("type");
  622.         var types = WiseStampUtils.getSignaturesFromPref().map(function (sig) {
  623.             return encodeURIComponent(sig.toLowerCase());
  624.         });
  625.         
  626.         for each(var t in types) {
  627.             try {
  628.                 pub.data.sigs[t] = loadSignatureFromConfig(t)
  629.             } catch(e) {
  630.                 //Load default
  631.                 pub.data.sigs[t] = loadSignatureFromConfig(DEFAULT_TYPE);
  632.             }
  633.         }
  634.     }
  635.  
  636.     function loadSignatureFromConfig(t) 
  637.     {
  638.         WiseStampUtils.log("[options.js::loadSignatureFromConfig] type = " + t + " >>>>");
  639.         
  640.         var tData = {};
  641.         tData.show = {}
  642.         tData.show.services = pub.PREFS.getCharPref(t + ".services");
  643.         tData.show.im = pub.PREFS.getCharPref(t + ".im");
  644.         tData.im = {}
  645.         tData.services = {};
  646.         var ims = pub.PREFS.getCharPref("im").split(",");
  647.         for (var i = 0; i < ims.length; i++) {
  648.             var im = ims[i];
  649.             var value = "";
  650.             if (pub.PREFS.prefHasUserValue(t + "." + im)) {
  651.                 value = pub.PREFS.getCharPref(t + "." + im);
  652.                 if (!value || value == "undefined") value = "";
  653.             }
  654.             tData.im[im] = value.split("\r\n");
  655.             if (!tData.im[im]) tData.im[im] = [];
  656.         }
  657.         var ids = pub.PREFS.getCharPref("services").split(",");
  658.         for (var i = 0; i < ids.length; i++) {
  659.             var sid = ids[i];
  660.             var value = "";
  661.             if (pub.PREFS.prefHasUserValue(t + "." + sid)) {
  662.                 value = pub.PREFS.getCharPref(t + "." + sid);
  663.                 if (!value || value == "undefined") value = "";
  664.             }
  665.             tData.services[sid] = value.split("\r\n");
  666.             if (!tData.services[sid]) tData.services[sid] = [];
  667.         }
  668.         tData.dir = pub.PREFS.getCharPref(t + ".dir");
  669.         tData.text = pub.PREFS.getComplexValue(t + ".text", Components.interfaces.nsISupportsString).data;
  670.         tData.advanced = pub.PREFS.getComplexValue(t + ".advanced", Components.interfaces.nsISupportsString).data;
  671.         tData.rsstitle = pub.PREFS.getComplexValue(t + ".rss-title", Components.interfaces.nsISupportsString).data;
  672.         tData.rssurl = pub.PREFS.getComplexValue(t + ".rss-url", Components.interfaces.nsISupportsString).data;
  673.         
  674.         tData.imFormat = {};
  675.         tData.servicesFormat = {};
  676.         
  677.         try {
  678.             tData.imFormat.hideTitle = WiseStampPrefs.PREFS.getBoolPref(t + ".im.hideTitle");
  679.             tData.imFormat.title = WiseStampPrefs.PREFS.getComplexValue(t + ".im.title", Components.interfaces.nsISupportsString).data;
  680.             tData.imFormat.showLabels = WiseStampPrefs.PREFS.getBoolPref(t + ".im.showLabels");
  681.             tData.imFormat.showIcons = WiseStampPrefs.PREFS.getBoolPref(t + ".im.showIcons");
  682.             
  683.             tData.servicesFormat.hideTitle = WiseStampPrefs.PREFS.getBoolPref(t + ".services.hideTitle");
  684.             tData.servicesFormat.title = WiseStampPrefs.PREFS.getComplexValue(t + ".services.title", Components.interfaces.nsISupportsString).data;
  685.             tData.servicesFormat.showLabels = WiseStampPrefs.PREFS.getBoolPref(t + ".services.showLabels");
  686.             tData.servicesFormat.showIcons = WiseStampPrefs.PREFS.getBoolPref(t + ".services.showIcons");
  687.         
  688.         } catch (e) // if no new fields - take defaults from the old
  689.         {
  690.             tData.imFormat.hideTitle = WiseStampPrefs.getBoolPref("hidechat",false);
  691.             tData.imFormat.title = WiseStampPrefs.getComplexPref("chat", pub.BUNDLE.GetStringFromName("extensions.wisestamp.chat"));
  692.             tData.imFormat.showLabels = WiseStampPrefs.getBoolPref("im.text",true);
  693.             tData.imFormat.showIcons = WiseStampPrefs.getBoolPref("im.icons",true);
  694.             
  695.             tData.servicesFormat.hideTitle = WiseStampPrefs.getBoolPref("hidecontactme",false);
  696.             tData.servicesFormat.title = WiseStampPrefs.getComplexPref("contactme", pub.BUNDLE.GetStringFromName("extensions.wisestamp.contactme"));
  697.             tData.servicesFormat.showLabels = WiseStampPrefs.getBoolPref("services.text",false);
  698.             tData.servicesFormat.showIcons = WiseStampPrefs.getBoolPref("services.icons",true);
  699.         }
  700.             
  701.         WiseStampUtils.log("[options.js::loadSignatureFromConfig] tData = " + WiseStampUtils.serialize(tData));
  702.         return tData;
  703.     }
  704.  
  705.     function storeData(aType)
  706.     {
  707.         var editor = document.getElementById("signature-" + editorMode);
  708.         if (editorMode == "wysiwyg") 
  709.             pub.data.sigs[aType].text = editor.contentDocument.body.innerHTML.replace(/<br\/?>+$/, "");
  710.         else
  711.             pub.data.sigs[aType].text = editor.value.replace(/(\n|\s)+$/gm, "");
  712.         
  713.         pub.data.sigs[aType].advanced = document.getElementById("signature-advanced").value.replace(/(\n|\s)+$/gm, "");
  714.         
  715.         pub.data.sigs[aType].dir = document.getElementById("signature-wysiwyg").contentDocument.dir;
  716.  
  717.         pub.data.sigs[aType].rsstitle = document.getElementById("rss-title").value;
  718.         pub.data.sigs[aType].rssurl = document.getElementById("rss-url").value;
  719.  
  720.         var eles = document.getElementById("im-box").getElementsByTagName("wisestamp-im");
  721.         var ims = pub.data.sigs[aType].im;
  722.         var showIM = [];
  723.         for (var i = 0; i < eles.length; i++)
  724.         {
  725.             ims[eles[i].service] = [];
  726.             showIM.push(eles[i].service);
  727.         }
  728.         for (var i = 0; i < eles.length; i++)
  729.         {
  730.             ims[eles[i].service].push(eles[i].value);
  731.         }
  732.         //pub.data.sigs[aType].im = ims;
  733.         //updateServicesFromDetails();
  734.         var eles = document.getElementById("social-services").getElementsByTagName("wisestamp-service");
  735.         var services = pub.data.sigs[aType].services; //{};
  736.         var showServices = [];
  737.         for (var i = 0; i < eles.length; i++)
  738.         {
  739.             services[eles[i].service] = [];
  740.             showServices.push(eles[i].service);
  741.         }
  742.         for (var i = 0; i < eles.length; i++)
  743.         {
  744.             services[eles[i].service].push(eles[i].value);
  745.         }
  746.         //pub.data.sigs[aType].services = services;
  747.         pub.data.sigs[aType].show.services = showServices.join(",");
  748.         pub.data.sigs[aType].show.im = showIM.join(",");
  749.     }
  750.  
  751.     function initGeneral()
  752.     {
  753.         try {
  754.             var label = document.getElementById(config_sig[0].prefix + pub.type).label;
  755.         }
  756.         catch (e)
  757.         {
  758.             alert("Internal Error :: Invalid type - " + pub.type);
  759.             return;
  760.         }
  761.          
  762.         //Sasha var curSig = document.getElementById("current_signature");
  763.         //Sasha curSig.value = pub.BUNDLE.GetStringFromName("currentSignatureMsg").replace("%s",label);
  764.         var setdefault = document.getElementById("setasdefault");
  765.         var isdefault = document.getElementById("isdefault");
  766.         if (pub.type == pub.data.type)
  767.         {
  768.             setdefault.hidden = true;
  769.             isdefault.hidden = false;
  770.         } else
  771.         {
  772.             setdefault.hidden = false;
  773.             isdefault.hidden = true;
  774.         }
  775.  
  776.         document.getElementById("rss-title").value = pub.data.sigs[pub.type].rsstitle;
  777.         document.getElementById("rss-url").value = pub.data.sigs[pub.type].rssurl;
  778.  
  779.         document.getElementById("rss-valid").value = "Validate";
  780.         document.getElementById("rss-valid").setAttribute("status", "ready");
  781.  
  782.         document.getElementById("signature_types_popup").parentNode.value = pub.type;
  783.  
  784.         var container = document.getElementById("signature_types_popup");
  785.         var nodes = container.childNodes
  786.         var len = nodes.length
  787.         for (var i = 0; i < len; i++)
  788.         {
  789.             if (nodes[i].getAttribute("value") == pub.type)
  790.             {
  791.                 /* remove node */
  792.                 container.parentNode.selectedIndex = i;
  793.                 break;
  794.             }
  795.         }
  796.     }
  797.  
  798.     function initEditor()
  799.     {
  800.         /* temporary workaround */
  801.         var editor = document.getElementById("signature-wysiwyg");
  802.         var html = pub.data.sigs[pub.type].text;
  803.         WiseStampUtils.log("[options.js::initEditor] HTML = " + html);
  804.         
  805.         WiseStampInitWYSIWYGEditor(editor, html, pub.data.sigs[pub.type].dir);
  806.  
  807.         editor = document.getElementById("signature-html");
  808.         //initSourceEditor(editor,html);
  809.         editor.value = html;
  810.  
  811.         document.getElementById("signature-advanced").value = pub.data.sigs[pub.type].advanced
  812.     }
  813.  
  814.     function initIM()
  815.     {
  816.         var ims = pub.PREFS.getCharPref(pub.type + ".im"),
  817.         counts = {};
  818.         if (ims.length > 0) 
  819.         {
  820.             var box = document.getElementById("im-box");
  821.             box.setAttribute("value", pub.data.sigs[pub.type].show.im);
  822.             ims = ims.split(",");
  823.             while (box.firstChild)
  824.                 box.removeChild(box.firstChild);
  825.                 
  826.             for (var i = 0; i < ims.length; i++)
  827.             {
  828.                 var im = ims[i];
  829.                 if (im in counts) counts[im]++;
  830.                 else counts[im] = 0;
  831.                     
  832.                 var num = counts[im];
  833.                 if (im && im.length > 0)
  834.                 {
  835.                     var item = document.createElement("wisestamp-im");
  836.                     item.setAttribute("service", im);
  837.                     var val = pub.data.sigs[pub.type].im[im][num];
  838.                     if (val) item.setAttribute("value", val);
  839.                     
  840.                     item.setAttribute("width", "170");
  841.                     /* insert before label */
  842.                     box.appendChild(item);
  843.                 }
  844.             }
  845.         }
  846.     }
  847.  
  848.     function initServices() {
  849.         var services = pub.PREFS.getCharPref(pub.type + ".services"),
  850.         counts = {};
  851.         if (services.length > 0) 
  852.         {
  853.             services = services.split(",");
  854.             var container = document.getElementById("social-services");
  855.             container.setAttribute("value", services.join(","));
  856.             while (container.firstChild)
  857.                 container.removeChild(container.firstChild);
  858.         
  859.             for (var i = 0; i < services.length; i++)
  860.             {
  861.                 var sid = services[i];
  862.                 if (sid in counts) counts[sid]++;
  863.                 else counts[sid] = 0;
  864.                     
  865.                 var num = counts[sid];
  866.                 var item = document.createElement("wisestamp-service");
  867.                 item.setAttribute("service", sid);
  868.                 var val = pub.data.sigs[pub.type].services[sid][num];
  869.                 if (val) item.setAttribute("value", val);
  870.  
  871.                 /* insert before label */
  872.                 container.appendChild(item);
  873.             }
  874.         }
  875.     }
  876.  
  877.     function updateRenamedSigs() 
  878.     {
  879.         var settings_container = document.getElementById(config_sig[1].id);
  880.         var menu_container = document.getElementById(config_sig[0].id);
  881.         var count = -1;
  882.         var sigsCount = settings_container.childNodes.length - 1;
  883.  
  884.         for (var iSig = 0; iSig < sigsCount; iSig++) 
  885.         {
  886.             var ele = settings_container.childNodes[iSig];
  887.             if (!ele.getAttribute) 
  888.                 continue;
  889.  
  890.             var txt = ele.getElementsByTagName("textbox")[0];
  891.             if (txt.value == "") 
  892.             {
  893.                 WiseStampUtils.log("options.js :: updateRenamedSigs :: " + pub.BUNDLE.GetStringFromName("empty_sig_name_error"));
  894.                 WiseStampUtils.alert("empty_sig_name_error");
  895.                 return false;
  896.             }
  897.         }
  898.  
  899.         for (var i = 0; i < sigsCount; i++) 
  900.         {
  901.             var ele = settings_container.childNodes[i];
  902.             if (!ele.getAttribute) 
  903.                 continue;
  904.                 
  905.             count++;
  906.             
  907.             var origval = ele.getAttribute("value");
  908.             var txt = ele.getElementsByTagName("textbox")[0];
  909.             
  910.             // signature was renamed
  911.             if (origval != txt.value)
  912.             {
  913.                 if (signatureExists(txt.value))
  914.                 {
  915.                     var error = WisestampSignatureFactory.strings.GetStringFromName("duplicate_signatures");
  916.                     error = error.replace("%s",txt.value);
  917.                     WiseStampUtils.alert2(error);
  918.                     return false;
  919.                 }
  920.             
  921.                 var oldshort = getTypeShortName(origval);
  922.                 var newshort = getTypeShortName(txt.value);
  923.                 
  924.                 ele.setAttribute("value", txt.value);
  925.  
  926.                 pub.data.sigs[newshort] = loadSignatureFromConfig(DEFAULT_TYPE);
  927.                 pub.data.sigs[newshort] = pub.data.sigs[oldshort];
  928.                 
  929.                 saveSignatureToConfig(newshort);
  930.                 delete pub.data.sigs[oldshort];
  931.                 
  932.                 loadSignatureFromConfig(newshort);
  933.                 settings.signatures[count] = txt.value;
  934.                 var ele2 = menu_container.childNodes[count];
  935.                 
  936.                 ele2.setAttribute("label", txt.value);
  937.                 ele2.setAttribute("value", getTypeShortName(txt.value));
  938.                 ele2.setAttribute("id", config_sig[0].prefix + getTypeShortName(txt.value));
  939.                 ele.setAttribute("id", config_sig[1].prefix + getTypeShortName(txt.value));
  940.  
  941.                 if (oldshort == pub.data.type) /*If it is the default, set as new default sig */
  942.                     pub.data.type = newshort;
  943.                 
  944.                 if (pub.type == oldshort) /* We are removing the current signature, reload the next sig */
  945.                     pub.setCurrentSignature(newshort, false);
  946.                 
  947.                 /* remove old signature from preferences */
  948.                 WiseStampPrefs.clearBranch(oldshort);
  949.             }
  950.         }
  951.         
  952.         return true;
  953.     }
  954.  
  955.     function saveSignatureToConfig(aType)
  956.     {
  957.         WiseStampUtils.log("options.js :: saveSignatureToConfig >>>");
  958.         var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
  959.         str.data = pub.data.sigs[aType].text;
  960.         pub.PREFS.setComplexValue(aType + ".text", Components.interfaces.nsISupportsString, str);
  961.         str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
  962.         str.data = pub.data.sigs[aType].advanced;
  963.         pub.PREFS.setComplexValue(aType + ".advanced", Components.interfaces.nsISupportsString, str);
  964.         str.data = pub.data.sigs[aType].rsstitle;
  965.         pub.PREFS.setComplexValue(aType + ".rss-title", Components.interfaces.nsISupportsString, str);
  966.         str.data = pub.data.sigs[aType].rssurl;
  967.         pub.PREFS.setComplexValue(aType + ".rss-url", Components.interfaces.nsISupportsString, str);
  968.  
  969.         pub.PREFS.setCharPref(aType + ".im", pub.data.sigs[aType].show.im);
  970.         for (var im in pub.data.sigs[aType].im)
  971.             pub.PREFS.setCharPref(aType + "." + im, pub.data.sigs[aType].im[im].join("\r\n"));
  972.  
  973.         for (var service in pub.data.sigs[aType].services)
  974.             pub.PREFS.setCharPref(aType + "." + service, pub.data.sigs[aType].services[service].join("\r\n"));
  975.  
  976.         pub.PREFS.setCharPref(aType + ".services", pub.data.sigs[aType].show.services);
  977.         pub.PREFS.setCharPref(aType + ".dir", pub.data.sigs[aType].dir);
  978.         
  979.         pub.PREFS.setBoolPref(aType + ".services.hideTitle", pub.data.sigs[aType].servicesFormat.hideTitle);
  980.         WiseStampPrefs.setComplexPref(aType + ".services.title", pub.data.sigs[aType].servicesFormat.title);
  981.         pub.PREFS.setBoolPref(aType + ".services.showLabels", pub.data.sigs[aType].servicesFormat.showLabels);
  982.         pub.PREFS.setBoolPref(aType + ".services.showIcons", pub.data.sigs[aType].servicesFormat.showIcons);
  983.         pub.PREFS.setBoolPref(aType + ".im.hideTitle", pub.data.sigs[aType].imFormat.hideTitle);
  984.         WiseStampPrefs.setComplexPref(aType + ".im.title", pub.data.sigs[aType].imFormat.title);
  985.         pub.PREFS.setBoolPref(aType + ".im.showLabels", pub.data.sigs[aType].imFormat.showLabels);
  986.         pub.PREFS.setBoolPref(aType + ".im.showIcons", pub.data.sigs[aType].imFormat.showIcons);
  987.     }
  988.  
  989.     ///////////////////////////////////////////////////////////////////////////
  990.     
  991.     function updateAccountStatus()
  992.     {
  993.         var user_suffix = "";
  994.         if (userLoggedIn) 
  995.         {
  996.             if (document.getElementById("account_login") != null)
  997.             {
  998.                 document.getElementById("account_login").setAttribute("disabled", "true");
  999.                 document.getElementById("email_edit").setAttribute("disabled", "true");
  1000.                 document.getElementById("password_edit").setAttribute("disabled", "true");
  1001.             }
  1002.             
  1003.             user_suffix = " :: " + userEmail;
  1004.             
  1005.         } else 
  1006.         {
  1007.             document.getElementById("account_login").removeAttribute("disabled");
  1008.             document.getElementById("email_edit").removeAttribute("disabled");
  1009.             document.getElementById("password_edit").removeAttribute("disabled");
  1010.             
  1011.             userEmail = null;
  1012.             userPassword = null;
  1013.             
  1014.             WiseStampUtils.userCode = null;
  1015.         }
  1016.         
  1017.         /*var prefwin = document.getElementById("BrowserPreferences");
  1018.         var title = prefwin.getAttribute('title');
  1019.         title = title + user_suffix;
  1020.         alert(title);
  1021.         prefwin.setAttribute('title',title);*/
  1022.     }
  1023.  
  1024.     pub.onLoginResponse = function (xml, email, password)
  1025.     {
  1026.         if (xml == null)
  1027.         {
  1028.             WiseStampUtils.alert("comm_action_failed");
  1029.             return false;
  1030.         }
  1031.         
  1032.         if (xml.nodes.result.text != "1") 
  1033.         {
  1034.             if (xml.nodes.error != undefined && xml.nodes.error.text.length > 0)
  1035.                 WiseStampUtils.alert2(xml.nodes.error.text);
  1036.             else
  1037.                 WiseStampUtils.alert("signatures_saved");
  1038.                         
  1039.             return false;
  1040.         }
  1041.  
  1042.         userLoggedIn = true;
  1043.  
  1044.         pub.PREFS.setCharPref("user_email", email);
  1045.         WiseStampUtils.storePassword(email,password);
  1046.         
  1047.         userEmail = email;
  1048.         userPassword = password;
  1049.         
  1050.         WiseStampUtils.setUserCode(xml.nodes.data.nodes.code.text);
  1051.         
  1052.         updateAccountStatus();
  1053.         syncSignaturesWithServer();
  1054.         SUPPORT_MULTI_SIG = (xml.nodes.data.nodes.plan.text == "corporate");
  1055.         updateMultipleSignaturesSupport(SUPPORT_MULTI_SIG);
  1056.     }
  1057.  
  1058.     function login(email, password, async) 
  1059.     {
  1060.         WiseStampUtils.log("options.js :: login >>> email/password = " + email + "/" + password);
  1061.         
  1062.         if (email == "") 
  1063.             return;
  1064.         
  1065.         userLoggedIn = false;
  1066.         pub.PREFS.setBoolPref("logged_in", true); // mark that login should be attempted on start-up
  1067.                 
  1068.         WiseStampComm.login(email, password, function(xml) { pub.onLoginResponse(xml,email,password); },async);
  1069.     }
  1070.  
  1071.     pub.onLogin = function () 
  1072.     {
  1073.         var email = document.getElementById("email_edit").value;
  1074.         var password = document.getElementById("password_edit").value;
  1075.  
  1076.         if (email == "" || password == "")
  1077.         {
  1078.             WiseStampUtils.alert("login_parameters_missing");
  1079.             return;
  1080.         }
  1081.     
  1082.         login(email, password, false);
  1083.     }
  1084.  
  1085.     pub.onLogout = function ()
  1086.     {
  1087.         userLoggedIn = false;
  1088.         updateAccountStatus();
  1089.         WiseStampPrefs.PREFS.setBoolPref("logged_in", false);
  1090.         WiseStampPrefs.PREFS.setBoolPref("synced", false);
  1091.         SUPPORT_MULTI_SIG = false;
  1092.         updateMultipleSignaturesSupport(SUPPORT_MULTI_SIG);
  1093.     }
  1094.  
  1095.     pub.loginInBackground = function ()
  1096.     {
  1097.         WiseStampUtils.log("[options.js :: loginInBackground] >>>>>");
  1098.         if (!SUPPORT_PREMIUM)
  1099.             return;
  1100.         
  1101.         var logged_in = WiseStampPrefs.getBoolPref("logged_in", false);
  1102.         var email = WiseStampPrefs.getCharPref("user_email", "");
  1103.         var password = WiseStampUtils.getPassword(email);
  1104.  
  1105.         WiseStampUtils.log("options.js :: loginInBackground :: logged_in = " + logged_in + ", email/password = " + email + "/" + password);
  1106.         var email_edit = document.getElementById("email_edit");
  1107.         var password_edit = document.getElementById("password_edit");
  1108.         
  1109.         if (email_edit != null) // may be executed from overlay
  1110.         {
  1111.             document.getElementById("email_edit").value = email;
  1112.             document.getElementById("password_edit").value = password;
  1113.         }
  1114.         
  1115.         if (logged_in)
  1116.             login(email,password,true);
  1117.     }
  1118.  
  1119.     pub.onRegister = function () 
  1120.     {
  1121.         var email = document.getElementById("email_edit").value;
  1122.         var password = document.getElementById("password_edit").value;
  1123.  
  1124.         var args = { email: email, password: password, result: null };
  1125.  
  1126.         var dlgURL = "chrome://wisestamp/content/registerDlg.xul";
  1127.         openDialog(dlgURL, "", "chrome,titlebar,toolbar,centerscreen,modal", args);
  1128.  
  1129.         if (args.result != true) 
  1130.             return;
  1131.  
  1132.         pub.onLogout();
  1133.         document.getElementById("email_edit").value = args.email;
  1134.         document.getElementById("password_edit").value = args.password;
  1135.  
  1136.         login(args.email, args.password, false);
  1137.     }
  1138.  
  1139.     function saveSignaturesToServer()
  1140.     {
  1141.         WiseStampUtils.log("options.js :: saveSignaturesToServer :: logged_in = " + userLoggedIn);
  1142.         
  1143.         if (!userLoggedIn)
  1144.             return;
  1145.         
  1146.         var signatures = [];
  1147.         
  1148.         for (var i = 0; i < settings.signatures.length; i++)
  1149.         {
  1150.             var typeName = settings.signatures[i];
  1151.             var type = getTypeShortName(typeName);
  1152.             
  1153.             var data = WiseStampUtils.serialize(pub.data.sigs[type]);
  1154.             
  1155.             // ampresand screws up the post data - fix it
  1156.             data = data.replace(/&/g,"%26");
  1157.             
  1158.             signatures[i] = {data: data, type: typeName};
  1159.         }
  1160.             
  1161.         //signature = escape(signature);
  1162.         var xml = WiseStampComm.saveSignatures(userEmail, userPassword, signatures);
  1163.         if (xml == null)
  1164.         {
  1165.             WiseStampUtils.alert("comm_action_failed");
  1166.             return false;
  1167.         }
  1168.         
  1169.         return true;
  1170.     }
  1171.     
  1172.     function signatureExists(typeName)
  1173.     {
  1174.         var type = getTypeShortName(typeName);
  1175.         return pub.data.sigs.hasOwnProperty(type);
  1176.     }
  1177.     
  1178.     function checkIfSignaturesChanged(signatures)
  1179.     {
  1180.         var sigs_changed = false;
  1181.         
  1182.         if (signatures.nodeCount != settings.signatures.length)
  1183.             sigs_changed = true;
  1184.         else
  1185.         {
  1186.             for (var i = 1; i <= signatures.nodeCount; i++)
  1187.             {
  1188.                 var typeName = signatures.nodes['item_' + i].nodes.type.text;
  1189.                 var type = getTypeShortName(typeName);
  1190.                 var exists = signatureExists(typeName);
  1191.                 if (!exists || 
  1192.                     WiseStampUtils.serialize(pub.data.sigs[type]) != signatures.nodes['item_' + i].nodes.data.text)
  1193.                 {
  1194.                     WiseStampUtils.log("options.js :: checkIfSignaturesChanged :: signature " + typeName + " was changed");
  1195.                     sigs_changed = true;
  1196.                     break;
  1197.                 }
  1198.             }
  1199.         }
  1200.         
  1201.         return sigs_changed;
  1202.     }
  1203.     
  1204.     function syncSignaturesWithServer()
  1205.     {
  1206.         if (!userLoggedIn)
  1207.             return;
  1208.         
  1209.         var xml = WiseStampComm.loadSignatures(userEmail,userPassword);
  1210.         if (xml == null)
  1211.         {
  1212.             WiseStampUtils.alert("action_failed");
  1213.             return;
  1214.         }
  1215.  
  1216.         var signatures = xml.nodes.data.nodes.signatures;
  1217.         WiseStampUtils.log("options.js :: syncSignaturesWithServer :: " + settings.signatures.length + " local, " + signatures.nodeCount + " on server");
  1218.         
  1219.         if (signatures.nodeCount == 0)
  1220.         {
  1221.             // todo: check for failure
  1222.             if (saveSignaturesToServer() == true)
  1223.                 WiseStampUtils.alert("first_login_message");
  1224.                 
  1225.             return;
  1226.         }
  1227.         
  1228.         var synced_already = WiseStampPrefs.getBoolPref("synced",false);
  1229.         if (synced_already)
  1230.         {
  1231.             loadSignaturesFromServer(signatures);
  1232.             return;
  1233.         }
  1234.             
  1235.         var question_result = null;
  1236.         for (var i = 1; i <= signatures.nodeCount; i++)
  1237.         {
  1238.             var typeName = signatures.nodes['item_'+i].nodes.type.text;
  1239.             var type = getTypeShortName(typeName);
  1240.             var signature_data = signatures.nodes['item_'+i].nodes.data.text;
  1241.  
  1242.             var exists = pub.data.sigs.hasOwnProperty(type);
  1243.             if (!exists || WiseStampUtils.serialize(pub.data.sigs[type]) != signature_data)
  1244.             {
  1245.                 WiseStampUtils.log("options.js :: syncSignaturesWithServer :: signature " + type + " was changed");
  1246.  
  1247.                 if (question_result == null)
  1248.                 {
  1249.                     question_result = WiseStampUtils.confirm(
  1250.                                         'application_name','signature_sync_question',
  1251.                                         'signature_sync_question_button_server',
  1252.                                         'signature_sync_question_button_local',
  1253.                                         'signature_sync_question_button_merge');
  1254.                                         
  1255.                     if (question_result == 0)
  1256.                     {
  1257.                         clearLocalSignatures();
  1258.                         loadSignaturesFromServer(signatures,true);
  1259.                         break;
  1260.                     }
  1261.                     
  1262.                     if (question_result == 1)
  1263.                     {
  1264.                         saveSignaturesToServer();
  1265.                         break;
  1266.                     }
  1267.                 }
  1268.  
  1269.                 // if signature with the same name already exists - change the name
  1270.                 var newTypeName = typeName;
  1271.                 if (exists)
  1272.                 {                                    
  1273.                     var iSignature = 1;
  1274.                     while (signatureExists(typeName + ' ('+iSignature+')'))
  1275.                         iSignature++;
  1276.                         
  1277.                     newTypeName = typeName + ' ('+iSignature+')';
  1278.                 }
  1279.                                                                     
  1280.                 loadSignatureFromServer(newTypeName,signature_data);                             
  1281.             }
  1282.         }
  1283.         
  1284.         saveSignaturesToServer();
  1285.         WiseStampPrefs.PREFS.setBoolPref("synced",true);
  1286.     }
  1287.             
  1288.     function loadSignatureFromServer(typeName,signature)
  1289.     {
  1290.         WiseStampUtils.log("options.js :: loadSignatureFromServer :: loading signature '" + typeName + "'");
  1291.  
  1292.         pub.deleteSignature(typeName,true);
  1293.         
  1294.         addNewSignatureElement(1, typeName);
  1295.         addNewSignatureElement(0, typeName);
  1296.         
  1297.         var type = getTypeShortName(typeName);
  1298.         pub.data.sigs[type] = signature;
  1299.             
  1300.         saveSignatureToConfig(type);
  1301.         settings.signatures.push(typeName);
  1302.     }
  1303.     
  1304.     function clearLocalSignatures()
  1305.     {
  1306.         for (var i = settings.signatures.length-1; i >= 0; i--)
  1307.             pub.deleteSignature(settings.signatures[i],true);
  1308.     }
  1309.     
  1310.     function loadSignaturesFromServer(signatures,changed)
  1311.     {
  1312.         WiseStampUtils.log("[options.js::loadSignaturesFromServer] >>>");
  1313.     
  1314.         if (changed != true)
  1315.             changed = checkIfSignaturesChanged(signatures);
  1316.  
  1317.         if (changed == false)
  1318.             return;
  1319.                             
  1320.         for (var i = 1; i <= signatures.nodeCount; i++)
  1321.         {
  1322.             var typeName = signatures.nodes['item_'+i].nodes.type.text;
  1323.             var data = signatures.nodes['item_'+i].nodes.data.text;
  1324.             
  1325.             WiseStampUtils.log("[options.js::loadSignaturesFromServer] name = " + typeName + ", data = " + data);
  1326.  
  1327.             var signature = WiseStampUtils.parseSerialized(data);
  1328.             loadSignatureFromServer(typeName,signature);
  1329.         }
  1330.         
  1331.         /*If it is the default, set a new default sig */
  1332.         var defaultStillExists = pub.data.sigs.hasOwnProperty(pub.data.type);
  1333.         if (!defaultStillExists)
  1334.             pub.data.type = getTypeShortName(settings.signatures[0]);
  1335.         
  1336.         pub.setCurrentSignature(pub.data.type,false);
  1337.         //pub.setCurrentAsDefault();
  1338.         
  1339.         // SASHA1 applySettings();
  1340.         WiseStampUtils.alert('signatures_loaded');
  1341.     }
  1342.     
  1343.     pub.onLoadSignatures = function()
  1344.     {
  1345.         if (userLoggedIn == false)
  1346.         {
  1347.             WiseStampUtils.alert("login_required","login_required_title");
  1348.             return;
  1349.         }
  1350.         
  1351.         var xml = WiseStampComm.loadSignatures(userEmail,userPassword);
  1352.         if (xml == null)
  1353.         {
  1354.             WiseStampUtils.alert("comm_action_failed");
  1355.             return;
  1356.         }
  1357.                     
  1358.         var signatures = xml.nodes.data.nodes.signatures;
  1359.         
  1360.         clearLocalSignatures();
  1361.         loadSignaturesFromServer(signatures);
  1362.     }
  1363.     
  1364.     pub.onSaveSignatures = function()
  1365.     {
  1366.         if (userLoggedIn == false)
  1367.         {
  1368.             WiseStampUtils.alert("login_required","login_required_title");
  1369.             return;
  1370.         }
  1371.         
  1372.         if (saveSignaturesToServer() == false)
  1373.             return false;
  1374.             
  1375.         WiseStampUtils.alert("signatures_saved");
  1376.         return true;
  1377.     }
  1378.  
  1379.     pub.onSocialFormatDlg = function()
  1380.     {
  1381.         var args = { settings: pub.data.sigs[pub.type].servicesFormat, result: null };
  1382.         
  1383.         var dlgURL = "chrome://wisestamp/content/dialogs/socialFormatDlg.xul";
  1384.         openDialog(dlgURL, "", "chrome,titlebar,toolbar,centerscreen,modal", args);
  1385.         
  1386.         if (args.result != true) 
  1387.             return;
  1388.         
  1389.         pub.data.sigs[pub.type].servicesFormat = args.settings;
  1390.     }
  1391.     
  1392.     pub.onImFormatDlg = function()
  1393.     {
  1394.         var args = { settings: pub.data.sigs[pub.type].imFormat, result: null };
  1395.         
  1396.         var dlgURL = "chrome://wisestamp/content/dialogs/imFormatDlg.xul";
  1397.         openDialog(dlgURL, "", "chrome,titlebar,toolbar,centerscreen,modal", args);
  1398.         
  1399.         if (args.result != true) 
  1400.             return;
  1401.         
  1402.         pub.data.sigs[pub.type].imFormat = args.settings;
  1403.     }
  1404.     
  1405.     ////////////////////////////////////////////////////////////////////////////
  1406.     
  1407.     pub.onResetSettings = function()
  1408.     {
  1409.         if (!confirm("You are about to reset all configuration. Are you sure?"))
  1410.             return; 
  1411.         
  1412.         WiseStampPrefs.clearBranch("");
  1413.     }
  1414.     
  1415.     pub.onExportSettings = function()
  1416.     {
  1417.         var file = WiseStampUtils.browseFile(false,"WiseStamp backup file","wst");
  1418.         if (file == null)
  1419.             return;
  1420.             
  1421.         WiseStampPrefs.export(file);
  1422.     }
  1423.             
  1424.     pub.onImportSettings = function()
  1425.     {
  1426.         var file = WiseStampUtils.browseFile(true,"WiseStamp backup file","wst");
  1427.         if (file == null)
  1428.             return;
  1429.             
  1430.         WiseStampPrefs.import(file);
  1431.     }
  1432.             
  1433.     pub.onExportLog = function()
  1434.     {
  1435.         var file = WiseStampUtils.browseFile(false,"WiseStamp log file","wlg");
  1436.         if (file == null)
  1437.             return;
  1438.         
  1439.         WiseStampUtils.exportLog(file);
  1440.     }
  1441.  
  1442.     function runTest(timeout)
  1443.     {
  1444.         if (pub.runningLoadTest == false)
  1445.         {
  1446.             document.getElementById('loadTestButton').setAttribute('label','Run load test...');
  1447.             return;
  1448.         }
  1449.             
  1450.         WiseStampComm.writeLog(WiseStampComm.LOG_EVENT_SIG_INSERT,"test_"+WiseStampUtils.getUserCode());
  1451.         setTimeout(function(){runTest(timeout);},timeout);
  1452.         
  1453.         document.getElementById('loadTestButton').setAttribute('label','Test running (click to stop). #' + pub.loadTestCount);
  1454.         pub.loadTestCount++;
  1455.     }
  1456.                 
  1457.     pub.onRunLoadTest = function(i)
  1458.     {
  1459.         if (pub.runningLoadTest == true)
  1460.         {
  1461.             pub.runningLoadTest = false;
  1462.             return;
  1463.         }
  1464.         
  1465.         var args = {
  1466.             title: "Define load test",
  1467.             intro: "", 
  1468.             items: {test_timeout: {type: "textbox", label: "Timeout between tests (ms)"}}
  1469.             };
  1470.         
  1471.         var dlgURL = "chrome://wisestamp/content/dialogs/formDlg.xul";
  1472.         openDialog(dlgURL, "", "chrome,titlebar,toolbar,centerscreen,modal", args);
  1473.         
  1474.         if (args.result != true) 
  1475.             return;
  1476.  
  1477.         pub.runningLoadTest = true;
  1478.         pub.loadTestCount = 0;            
  1479.         runTest(args.items.test_timeout.value);
  1480.     }
  1481.             
  1482.     pub.showPremiumInfo = function(event)
  1483.     {
  1484.         document.getElementById("BrowserPreferences").showPane(document.getElementById("paneContent"));
  1485.     }
  1486.     
  1487.     return pub;
  1488. } ();